<template>
  <div class="employee-list-container">
    <!-- 搜索和添加区域 -->
    <div class="list-header">
      <el-input
          v-model="searchQuery"
          placeholder="输入员工姓名搜索"
          clearable
          style="width: 300px"
          @clear="handleSearch"
          @keyup.enter="handleSearch"
      >
        <template #prefix>
          <el-icon><Search /></el-icon>
        </template>
      </el-input>

      <el-button
          type="primary"
          @click="handleAddEmployee"
      >
        <el-icon><Plus /></el-icon>
        添加员工
      </el-button>
    </div>

    <!-- 员工表格 -->
    <el-table
        :data="filteredEmployees"
        border
        stripe
        style="width: 100%"
        v-loading="loading"
    >
      <el-table-column prop="username" label="员工账号" width="200" align="center"/>
      <el-table-column prop="name" label="员工姓名" width="200" align="center" />
      <el-table-column prop="sex" label="性别" width="100" align="center">
        <template #default="{ row }">
          {{ row.sex || '-' }}
        </template>
      </el-table-column>
      <el-table-column prop="phone" label="手机号码" width="200" align="center" />
      <el-table-column prop="idCard" label="身份证号" width="300" align="center">
        <template #default="{ row }">
          {{ row.idNumber? formatIdCard(row.idNumber) : '-' }}
        </template>
      </el-table-column>
      <el-table-column prop="status" label="账号状态" width="100" align="center">
        <template #default="{ row }">
          <el-tag :type="row.status === 1 ? 'success' : 'danger'">
            {{ row.status === 1 ? '正常' : '封禁' }}
          </el-tag>
        </template>
      </el-table-column>

      <el-table-column label="操作" width="250" fixed="right" align="center">
        <template #default="{ row }">
          <el-button
              size="small"
              @click="handleEdit(row)"
          >
            编辑
          </el-button>
          <el-button
              size="small"
              :type="row.status === 1 ? 'danger' : 'success'"
              @click="handleToggleStatus(row)"
          >
            {{ row.status === 1 ? '停用' : '启用' }}
          </el-button>
        </template>
      </el-table-column>
    </el-table>

    <!-- 分页控件 -->
    <Pagination
        :currentPage="currentPage"
        :pageSize="pageSize"
        :total="total"
        @update:currentPage="handlePageChange"
        @update:pageSize="handlePageSizeChange"
    />

    <!-- 添加/编辑弹窗组件 -->
    <EmployeeDialog
        v-model="dialogVisible"
        :current-employee="currentEmployee"
        @refresh="fetchEmployees"
    />
  </div>
</template>

<script setup>
import { ref, computed, onMounted } from 'vue'
import { Search, Plus } from '@element-plus/icons-vue'
import EmployeeDialog from './EmployeeDialog.vue'
import Pagination from "@/components/common/Pagination.vue";
import {ElMessage, ElMessageBox} from "element-plus";
import {employeeList, updateEmployee} from "@/api/employee";

// 状态管理
const loading = ref(false) // 加载状态
const employees = ref([]) // 员工列表
const searchQuery = ref('')// 搜索关键词

const dialogVisible = ref(false)
const currentEmployee = ref(null)// 当前编辑的员工

//分页相关
const currentPage = ref(1)
const pageSize = ref(10)
const total = ref(0)

// 格式化身份证显示
const formatIdCard = (idNumber) => {
  if (!idNumber || idNumber.length !== 18) return idNumber || '-'
  return `${idNumber.substring(0, 6)}****${idNumber.substring(14)}`
}

/* 获取员工初始化列表*/
const fetchEmployees = async () => {
  loading.value = true
  try {
    const params = {
      pageNo: currentPage.value,
      pageSize: pageSize.value,
      search: searchQuery.value
    }//传递的参数
    const res = await employeeList(params);
    await new Promise(resolve => setTimeout(resolve, 300)) // 模拟延迟
    if(res.code === '200'){
      employees.value = res.data.records
      total.value = res.data.total
    }else{
      ElMessage.error(res.msg||'获取员工列表失败');
    }
  } finally {
    loading.value = false
  }
}
// 搜索处理
const handleSearch = () => {
  currentPage.value = 1
  fetchEmployees()
}

// 过滤后的员工列表
const filteredEmployees = computed(() => {
  return employees.value.filter(emp =>
      emp.name.includes(searchQuery.value) ||
      emp.username.includes(searchQuery.value)
  )
})

// 添加员工
const handleAddEmployee = () => {
  currentEmployee.value = null
  dialogVisible.value = true
}

// 编辑员工
const handleEdit = (row) => {
  currentEmployee.value = { ...row }
  dialogVisible.value = true
}

// 切换状态
const handleToggleStatus = async (row) => {
  try {
    // 显示确认对话框
    await ElMessageBox.confirm(
        `确认要${row.status === 1 ? '停用' : '启用'}该员工账号吗？`,
        '操作确认',
        {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning',
        }
    )

    loading.value = true
    // 执行状态修改
    const params = {
    id: row.id,
      status: row.status === 1 ? 0 : 1
    }
    const res = await updateEmployee(params)

    if (res.code === '200') {
      ElMessage.success(`已${row.status === 1 ? '停用' : '启用'}该账号`)
      row.status = row.status === 1 ? 0 : 1 // 前端状态更新
    } else {
      ElMessage.error(res.msg || '操作失败')
    }

  } catch (error) {
    // 用户点击取消时，error === 'cancel'
    if (error !== 'cancel') {
      ElMessage.error('操作失败: ' + (error.message || error))
    }
  } finally {
    loading.value = false
  }
}

// 分页处理函数
const handlePageChange = (newPage) => {
  currentPage.value = newPage;
  fetchEmployees()
};

const handlePageSizeChange = (newSize) => {
  pageSize.value = newSize;
  currentPage.value = 1; // 必须重置页码
  fetchEmployees()
};
// 初始化加载
onMounted(() => {
  fetchEmployees()
})
</script>

<style scoped>
.employee-list-container {
  padding: 20px;
  background: #fff;
  border-radius: 4px;
}

.list-header {
  display: flex;
  justify-content: space-between;
  margin-bottom: 20px;
}

.pagination-container {
  display: flex;
  justify-content: flex-end;
  margin-top: 20px;
}

.el-table {
  margin-top: 10px;
}

.el-button + .el-button {
  margin-left: 8px;
}
</style>